/**
 * <p>Title: ProduceStatistics.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张志芳
 * @version 1.0
 * <pre>Histroy:
 *          2011-10-22 下午04:50:22  张志芳  Create
 *</pre>
 */
package com.baosight.sczx.common.zm.cInterface.cp;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baosight.iplat4j.core.ei.EiBlock;
import com.baosight.iplat4j.core.ei.EiInfo;
import com.baosight.iplat4j.core.spring.SpringApplicationContext;
import com.baosight.iplat4j.dao.Dao;
import com.baosight.sczx.common.zm.basetools.StaticTools;
import com.baosight.sczx.common.zm.basetools.TablePk;
import com.baosight.sczx.common.zm.cInterface.cs.SystemSettingCP;

/**
 * 生产数据统计
 * <p>Title: ProduceStatistics.java</p>
 * <p>Description: </p>
 * <p>Copyright: Baosight Software LTD.co Copyright (c) 2002</p>
 * <p>Company: Baosight Software</p>
 * @author 张志芳
 * @version 1.0
 * <pre>Histroy:
 *          2011-10-22 下午04:50:22  张志芳  Create
 *</pre>
 */
public class ProduceStatistics {
	
	private static Dao dao = (Dao)SpringApplicationContext.getBean("dao");

	/**
	 * 更新验收值(验收发布时)
	 * <p>Function: updateValidate</p>
	 * <p>Description: </p>
	 * <p>return value:Boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-22下午06:23:28 张志芳
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Boolean updateValidate(EiInfo inInfo, String sumName)
	{
		try {
			EiBlock block = inInfo.getBlock("result");
			if(block==null) return false;
			for(int i=0; i<block.getRowCount(); i++)
			{
				Map map = new HashMap();
				map.put("fdProjectId", block.getCell(i, "fdProjectId"));
				map.put("fdDepartmentId", block.getCell(i, "fdDepartmentId"));
				map.put("fdYear", block.getCell(i, "fdYear"));
				map.put("fdMonth", block.getCell(i, "fdMonth"));
				List<Map> list = dao.query("ZMCPProduceStatistics.validate", map);
				if(list.size()>0)
				{						
					String befor = list.get(0).get("fdValidateSum")==null?"0":list.get(0).get("fdValidateSum").toString();
					map.put("fdValidateSum",Double.parseDouble(befor) + Double.parseDouble(block.getCellStr(i, sumName)));								
					dao.update("ZMCPProduceStatistics.updateValidate", map);
				}
				else
				{
					map.put("fdValidateSum", block.getCell(i, sumName));
					map.put("fdKeyId", TablePk.getInstance().getNextValue("T_CP_PRODUCE_STATISTICS"));					
					map.put("fdDepartmentName", block.getCell(i, "fdDepartment"));
					dao.insert("ZMCPProduceStatistics.insert", map);
				}
			}
		} catch (Exception e) {
			System.out.println("生产数据统计表中的验收量更新失败: " + e.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * 更新计划值（在计划生效时累计）
	 * <p>Function: updatePlan1</p>
	 * <p>Description: </p>
	 * <p>return value:Boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-22下午06:23:28 张志芳
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Boolean updatePlan1(EiInfo inInfo)
	{
		try {
			EiBlock block = inInfo.getBlock("result");
			if(block==null) return false;
			for(int i=0; i<block.getRowCount(); i++)
			{
				Map map = new HashMap();
				map.put("fdProjectId", block.getCell(i, "fdProjectId"));
				map.put("fdDepartmentId", block.getCell(i, "fdDepartmentId"));
				map.put("fdYear", block.getCell(i, "fdPlanYear"));
				map.put("fdMonth", block.getCell(i, "fdPlanMonth"));
				List<Map> list = dao.query("ZMCPProduceStatistics.validate", map);
				if(list.size()>0)
				{						
					String befor = list.get(0).get("fdPlanSum")==null?"0":list.get(0).get("fdPlanSum").toString();
					map.put("fdPlanSum",Double.parseDouble(befor) + Double.parseDouble(block.getCellStr(i, "fdPlanSum")));										
					dao.update("ZMCPProduceStatistics.updatePlan", map);
				}
				else
				{
					map.put("fdPlanSum", block.getCell(i, "fdPlanSum"));
					map.put("fdKeyId", TablePk.getInstance().getNextValue("T_CP_PRODUCE_STATISTICS"));					
					map.put("fdDepartmentName", block.getCell(i, "fdDepartment"));
					dao.insert("ZMCPProduceStatistics.insert", map);
				}
			}
		} catch (Exception e) {
			System.out.println("生产数据统计表中的计划量更新失败: " + e.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * 更新计划值（在计划调整时减去值）
	 * <p>Function: updatePlan2</p>
	 * <p>Description: </p>
	 * <p>return value:Boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-22下午06:23:28 张志芳
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Boolean updatePlan2(EiInfo inInfo)
	{
		try {
			EiBlock block = inInfo.getBlock("result");
			if(block==null) return false;
			for(int i=0; i<block.getRowCount(); i++)
			{
				Map map = new HashMap();
				map.put("fdProjectId", block.getCell(i, "fdProjectId"));
				map.put("fdDepartmentId", block.getCell(i, "fdDepartmentId"));
				map.put("fdYear", block.getCell(i, "fdPlanYear"));
				map.put("fdMonth", block.getCell(i, "fdPlanMonth"));
				List<Map> list = dao.query("ZMCPProduceStatistics.validate", map);
				if(list.size()>0)
				{						
					String befor = list.get(0).get("fdPlanSum")==null?"0":list.get(0).get("fdPlanSum").toString();
					map.put("fdPlanSum",Double.parseDouble(befor) - Double.parseDouble(block.getCellStr(i, "fdPlanSum")));										
					dao.update("ZMCPProduceStatistics.updatePlan", map);
				}				
			}
		} catch (Exception e) {
			System.out.println("生产数据统计表中的计划量更新失败: " + e.getMessage());
			return false;
		}
		return true;
	}
	
	
	/**
	 * 更新上报值（在采煤掘进度上报时累计）type分为采煤（fdMineSum）和掘进（fdMoveLength）
	 * <p>Function: updateReport</p>
	 * <p>Description: </p>
	 * <p>return value:Boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-22下午06:23:28 张志芳
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Boolean updateReport(EiInfo inInfo, String type)
	{
		if(type==null)
		{
			type="fdMineSum";
		}
		try {
			EiBlock block = inInfo.getBlock("result");
			if(block==null) return false;
			for(int i=0; i<block.getRowCount(); i++)
			{
				Map map = new HashMap();
				map.put("fdProjectId", block.getCell(i, "fdProjectId"));
				map.put("fdDepartmentId", block.getCell(i, "fdReportDepartmentId"));
				String[] ym = getStatisticsYearMonth(block.getCellStr(i, "fdDate"));
				map.put("fdYear", ym[0]);
				map.put("fdMonth", ym[1]);
				List<Map> list = dao.query("ZMCPProduceStatistics.validate", map);
				if(list.size()>0)
				{						
					String befor = list.get(0).get("fdReportSum")==null?"0":list.get(0).get("fdReportSum").toString();
					map.put("fdReportSum",Double.parseDouble(befor) + Double.parseDouble(block.getCellStr(i, type)));										
					dao.update("ZMCPProduceStatistics.updateReport", map);
				}
				else
				{
					map.put("fdReportSum", block.getCell(i, type));
					map.put("fdKeyId", TablePk.getInstance().getNextValue("T_CP_PRODUCE_STATISTICS"));					
					map.put("fdDepartmentName", block.getCell(i, "fdReportDepartment"));
					dao.insert("ZMCPProduceStatistics.insert", map);
				}
			}
		} catch (Exception e) {
			System.out.println("生产数据统计表中的上报量更新失败: " + e.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * 更新上报值（在调度日志中采煤掘进度退回时减值）type分为采煤（fdMineSum）和掘进（fdMoveLength）
	 * <p>Function: updateReport2</p>
	 * <p>Description: </p>
	 * <p>return value:Boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-22下午06:23:28 张志芳
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Boolean updateReport2(EiInfo inInfo, String type)
	{
		if(type==null)
		{
			type="fdMineSum";
		}
		try {			
			EiBlock block = inInfo.getBlock("result");
			if(block==null) return false;
			for(int i=0; i<block.getRowCount(); i++)
			{
				Map map = new HashMap();
				map.put("fdProjectId", block.getCell(i, "fdProjectId"));
				map.put("fdDepartmentId", block.getCell(i, "fdReportDepartmentId"));
				String[] ym = getStatisticsYearMonth(block.getCellStr(i, "fdDate"));
				map.put("fdYear", ym[0]);
				map.put("fdMonth", ym[1]);
				List<Map> list = dao.query("ZMCPProduceStatistics.validate", map);
				if(list.size()>0)
				{						
					String befor = list.get(0).get("fdReportSum")==null?"0":list.get(0).get("fdReportSum").toString();
					map.put("fdReportSum",Double.parseDouble(befor) - Double.parseDouble(block.getCellStr(i, type)));										
					dao.update("ZMCPProduceStatistics.updateReport", map);
				}				
			}			
		} catch (Exception e) {
			System.out.println("生产数据统计表中的上报量更新失败: " + e.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * 更新调度值（在调度日志中采煤掘进度上报时累计）type分为采煤（fdMineSum）和掘进（fdMoveLength）
	 * <p>Function: updateDispatch</p>
	 * <p>Description: </p>
	 * <p>return value:Boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-22下午06:23:28 张志芳
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Boolean updateDispatch(EiInfo inInfo,String type)
	{
		if(type==null)
		{
			type="fdMineSum";
		}
		try {
			EiBlock block = inInfo.getBlock("result");
			if(block==null) return false;
			for(int i=0; i<block.getRowCount(); i++)
			{
				Map map = new HashMap();
				map.put("fdProjectId", block.getCell(i, "fdProjectId"));
				map.put("fdDepartmentId", block.getCell(i, "fdReportDepartmentId"));
				String[] ym = getStatisticsYearMonth(block.getCellStr(i, "fdDate"));
				map.put("fdYear", ym[0]);
				map.put("fdMonth", ym[1]);
				List<Map> list = dao.query("ZMCPProduceStatistics.validate", map);
				if(list.size()>0)
				{						
					String befor = list.get(0).get("fdDispatchSum")==null?"0":list.get(0).get("fdDispatchSum").toString();
					map.put("fdDispatchSum",Double.parseDouble(befor) + Double.parseDouble(block.getCellStr(i, type)));										
					dao.update("ZMCPProduceStatistics.updateDispatch", map);
				}
				else
				{
					map.put("fdDispatchSum", block.getCell(i, type));
					map.put("fdKeyId", TablePk.getInstance().getNextValue("T_CP_PRODUCE_STATISTICS"));					
					map.put("fdDepartmentName", block.getCell(i, "fdReportDepartment"));
					dao.insert("ZMCPProduceStatistics.insert", map);
				}
			}
		} catch (Exception e) {
			System.out.println("生产数据统计表中的计划量更新失败: " + e.getMessage());
			return false;
		}
		return true;
	}
	
	/**
	 * 更新调度值（在调度日志中采煤掘进度退回时减值）type分为采煤（fdMineSum）和掘进（fdMoveLength）
	 * <p>Function: updateDispatch2</p>
	 * <p>Description: </p>
	 * <p>return value:Boolean</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-6-21上午02:12:01 张志芳
	 * </p>
	 *
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	public static Boolean updateDispatch2(EiInfo inInfo,String type)
	{
		try {
			EiBlock block = inInfo.getBlock("result");
			if(block==null) return false;
			for(int i=0; i<block.getRowCount(); i++)
			{
				Map map = new HashMap();
				map.put("fdProjectId", block.getCell(i, "fdProjectId"));
				map.put("fdDepartmentId", block.getCell(i, "fdReportDepartmentId"));
				String[] ym = getStatisticsYearMonth(block.getCellStr(i, "fdDate"));
				map.put("fdYear", ym[0]);
				map.put("fdMonth", ym[1]);
				List<Map> list = dao.query("ZMCPProduceStatistics.validate", map);
				if(list.size()>0)
				{						
					String befor = list.get(0).get("fdDispatchSum")==null?"0":list.get(0).get("fdDispatchSum").toString();
					map.put("fdDispatchSum",Double.parseDouble(befor) - Double.parseDouble(block.getCellStr(i, type)));										
					dao.update("ZMCPProduceStatistics.updateDispatch", map);
				}				
			}
		} catch (Exception e) {
			System.out.println("生产数据统计表中的调度量更新失败: " + e.getMessage());
			return false;
		}
		return true;
	}

	/**
	 * 判断日期对应的统计年和月
	 * <p>Function: getStatisticsYearMonth</p>
	 * <p>Description: </p>
	 * <p>return value:String[]</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2011-10-27下午08:26:54 张志芳
	 * </p>
	 *
	 */
	@SuppressWarnings("deprecation")
	public static String[] getStatisticsYearMonth(String date)
	{
		String[] result=new String[2];
		int begin = SystemSettingCP.getInstance().getBeginDate();
		String mode = SystemSettingCP.getInstance().getReportMonthMode();
		
		String year = "".equals(StaticTools.getYearStr(date))?StaticTools.getYear():StaticTools.getYearStr(date);
		String month = "".equals(StaticTools.getMonthStr(date))?StaticTools.getMonth():StaticTools.getMonthStr(date);
		int day = StaticTools.stringToDate(date,"yyyy-MM-dd").getDate();
		if(begin>day)
		{
			if("0".equals(mode))
			{
				result[0]=year;
				result[1]=Integer.toString(Integer.parseInt(month));
			}
			else
			{
				if(month.equals("01"))
				{
					result[0]=Integer.toString((Integer.parseInt(year)-1));
					result[1]="12";
				}
				else
				{
					result[0]=year;
					result[1]=Integer.toString((Integer.parseInt(month)-1));
				}
			}
		}
		else
		{
			if("0".equals(mode))
			{
				if(month.equals("12"))
				{
					result[0]=Integer.toString((Integer.parseInt(year)+1));
					result[1]="1";
				}
				else
				{
					result[0]=year;
					result[1]=Integer.toString((Integer.parseInt(month)+1));
				}
			}
			else
			{
				result[0]=year;
				result[1]=Integer.toString(Integer.parseInt(month));
			}
		}
		return result;
	}
	
	/**
	 * 获取某生产月的开始日期
	 * <p>Function: getStatisticsBeginDate</p>
	 * <p>Description: </p>
	 * <p>return value:String</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-2-7下午05:02:34 张志芳
	 * </p>
	 *
	 */
	public static String getStatisticsBeginDate(String year, String month)
	{
		String result="";
		int begin = SystemSettingCP.getInstance().getBeginDate();
		String mode = SystemSettingCP.getInstance().getReportMonthMode();
		
		if("0".equals(mode))
		{
			month=Integer.toString(Integer.parseInt(month)-1);
			if(Integer.parseInt(month)==0)
			{
				year=Integer.toString(Integer.parseInt(year)-1);
				month="12";
			}
		}
		
	    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置显示格式
	    result=df.format(StaticTools.stringToDate(year+"-"+month+"-"+begin,"yyyy-MM-dd"));
	    
		return result;
	}
	
	/**
	 * 获取某生产月的结束日期
	 * <p>Function: getStatisticsEndDate</p>
	 * <p>Description: </p>
	 * <p>return value:String</p>
	 * <p>throws Exception:</p>
	 * <p>History:
	 *    2012-2-8下午05:07:22 张志芳
	 * </p>
	 *
	 */
	public static String getStatisticsEndDate(String year, String month)
	{
		String result="";
		int begin = SystemSettingCP.getInstance().getBeginDate();
		String mode = SystemSettingCP.getInstance().getReportMonthMode();
		
		begin=begin-1;
		if("0".equals(mode))
		{	
			if(begin==0)
			{
				if(Integer.parseInt(month)-1 == 0)
				{
					result=StaticTools.getLastDay(Integer.parseInt(year)-1+"-12-01");
					return result;
				}	
				result=StaticTools.getLastDay(year+"-"+Integer.toString(Integer.parseInt(month)-1)+"-01");
				return result;			
			}
		    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置显示格式
		    result=df.format(StaticTools.stringToDate(year+"-"+month+"-"+begin,"yyyy-MM-dd"));
		    
			return result;
		}
		else
		{
			if(begin==0)
			{
				result=StaticTools.getLastDay(year+"-"+month+"-01");
				return result;	
			}
			if("12".equals(month))
			{
			    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置显示格式
			    result=df.format(StaticTools.stringToDate((Integer.parseInt(year)+1)+"-01-"+begin,"yyyy-MM-dd"));
			    
				return result;
			}
		    DateFormat df = new SimpleDateFormat("yyyy-MM-dd");//设置显示格式
		    result=df.format(StaticTools.stringToDate(year+"-"+(Integer.parseInt(month)+1)+"-"+begin,"yyyy-MM-dd"));
		    
			return result;
		}
	}
}
